from Bases import BaseObject
from baseview import BaseView
from .. import editors
from ..bases import widgets


class DeviceControlView(BaseView):
    _view_name = 'Device Control'
    def init_view(self, **kwargs):
        self.topwidget = widgets.Frame(label='Device Control')
        self.hbox = widgets.HBox()
        
        self.table = widgets.Table(cols=4)
        self.group_faders = {}
        for group in self.MainController.Groups.indexed_items.itervalues():
            self.build_group_fader(group)
        self.update_table_widgets()
        self.hbox.add_widget(self.table)
        
        self.selected_controls = SelectedDeviceControls()
        self.hbox.add_widget(self.selected_controls.topwidget)
        
        self.topwidget.add_widget(self.hbox)
        
        self.MainController.Groups.bind(child_update=self.on_mc_Groups_child_update)
        
    def unlink(self):
        super(DeviceControlView, self).unlink()
        self.MainController.Groups.unbind(self)
        for f in self.group_faders.itervalues():
            f.unbind(self)
            f.unlink()
        
    def build_group_fader(self, group):
        f = GroupFader(group=group, parent=self)
        f.bind(selected=self.on_group_selected, 
               Index=self.on_group_Index_changed)
        #self.table.add_widget(f.topwidget, index=f.kivy_index)
        self.group_faders[f.Index] = f
        
    def update_table_widgets(self):
        self.table.clear_widgets()
        keys = self.group_faders.keys()
        keys.sort()
        #keys.reverse()
        for key in keys:
            f = self.group_faders[key]
            self.table.add_widget(f.topwidget)
            
    def remove_group_fader(self, group):
        f = self.group_faders.get(group.Index)
        if f is None:
            return
        f.unbind(self)
        self.table.remove_widget(f.topwidget)
        f.unlink()
        del self.group_faders[group.Index]
        
    def on_group_Index_changed(self, **kwargs):
        f = kwargs.get('obj')
        old = kwargs.get('old')
        value = kwargs.get('value')
        if old in self.group_faders:
            del self.group_faders[old]
        self.group_faders[value] = f
        self.update_table_widgets()
            
    def on_group_selected(self, **kwargs):
        obj = kwargs.get('obj')
        state = kwargs.get('value')
        if state:
            for key, val in self.group_faders.iteritems():
                if key != obj.Index:
                    val.selected = False
            self.selected_controls.selected_object = obj.group
                    
    def on_mc_Groups_child_update(self, **kwargs):
        mode = kwargs.get('mode')
        group = kwargs.get('obj')
        if mode == 'add':
            self.build_group_fader(group)
        elif mode == 'remove':
            self.remove_group_fader(group)
        else:
            return
        self.update_table_widgets()
class GroupFader(BaseObject):
    _Properties = {'selected':dict(default=False, quiet=True)}
    def __init__(self, **kwargs):
        super(GroupFader, self).__init__(**kwargs)
        self.group = kwargs.get('group')
        self.parent = kwargs.get('parent')
        self.Index = self.group.Index
        self.group.bind(Index=self.on_group_Index_set, 
                        property_changed=self.on_group_property_changed)
        self.topwidget = widgets.Frame()
        self.label_widgets = {}
        for key in ['Index', 'name']:
            w = widgets.Label(text=str(getattr(self.group, key)), size_hint_y=.1)
            self.topwidget.add_widget(w)
            self.label_widgets[key] = w
        self.fader = widgets.VSlider(Property=(self.group.AttributeGroups['Dimmer'], 'value'))
        self.topwidget.add_widget(self.fader.topwidget)
        self.select_btn = widgets.ToggleBtn(label='Select', Property=(self, 'selected'), size_hint_y=.1)
        self.topwidget.add_widget(self.select_btn.widget)
    def unlink(self):
        super(GroupFader, self).unlink()
        self.group.unbind(self)
        for w in self.label_widgets.itervalues():
            w.unlink()
        self.fader.unlink()
    def on_group_Index_set(self, **kwargs):
        self.Index = kwargs.get('value')
    def on_group_property_changed(self, **kwargs):
        prop = kwargs.get('Property')
        value = kwargs.get('value')
        lbl = self.label_widgets.get(prop.name)
        if not lbl:
            return
        lbl.text = str(value)
        
class SelectedDeviceControls(BaseObject):
    def __init__(self, **kwargs):
        self._selected_object = None
        super(SelectedDeviceControls, self).__init__(**kwargs)
        self.topwidget = widgets.VBox()
        
        hbox = widgets.HBox()
        self.controls = {}
        
        w = widgets.ColorPicker()
        hbox.add_widget(w.topwidget)
        self.controls['Color'] = w
        
        w = widgets.XYPad()
        hbox.add_widget(w.topwidget)
        self.controls['Position'] = w
        
        self.topwidget.add_widget(hbox)
        hbox2 = widgets.HBox()
        self.topwidget.add_widget(hbox2)
        
    @property
    def selected_object(self):
        return self._selected_object
    @selected_object.setter
    def selected_object(self, value):
        if value:
            if value == self._selected_object:
                return
            self._selected_object = value
            for key, val in self.controls.iteritems():
                group = value.AttributeGroups.get(key)
                if group:
                    val.Property = (group, 'value')
                else:
                    val.Property = None
        else:
            self._selected_object = None
            for c in self.controls.itervalues():
                c.Property = None
